package x.x.x;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ReadXml {
    //配置文件名,默认从项目根目录开始计算,根目录是F:\CODE\Web\JavaStep\
    private static String filename = "WebRoot/WEB-INF/conf.xml";
    private static Config config;
    
    
    /**
     * 从配置文件中读取参数并保存到config
     *@author hanxy17
     * 如修改方法体请自行修改作者信息
     * 当前作者只对自己编写内容负责
     * 2017年3月8日上午10:20:12
     * @return
     */
    public static Config loadconfig(){
        if(config == null){
            config = getconfig();
        }
        return config;
    }
    
    private static Config getconfig(){
        Config config = new Config();
        try {
            File file = new File(filename);
//            file.getAbsolutePath();//获得当前代码的完全路径
            if(!file.exists()){
                System.err.println("Error : Config file doesn't exist!");
                System.exit(1);
            }
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element root = doc.getRootElement();
            Iterator<Element> iterator = root.elementIterator("VALUE");
            Element data = iterator.next();
            
            config.server = data.elementText("server").trim();
            config.user = data.elementText("user").trim();
            config.password = data.elementText("pass").trim();
            config.port = data.elementText("port").trim();
            config.dbname = data.elementText("dbname").trim();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return config;
    }
    
    public static class Config{
        public String server;
        public String user;
        public String password;
        public String port;
        public String dbname;
        
        public String getConnString(){
            return new StringBuffer().append("result:").append("<server,").append(server).append(">,<user,").append(user).append(">").toString();
        }
    }
    
    
    public static void main(String[] args) {
        Config config = loadconfig();
        System.err.println(config.getConnString());
    }
}
